<template>
  <el-dialog :model-value="dialogVisible" :title="title" width="50%" align-center @closed="handleCancel">
    <label class="tip" v-if="props.mode == 'saveAs'">* 勾选以下版本可覆盖保存</label>
    <x-table
      ref="refTable"
      name="表单版本"
      :height="tableHeight"
      :columns="columns"
      :data="tableData.resp.list"
      :total="tableData.resp.total"
      :loading="tableData.loading"
      :init-query="false"
      :showColumnTbar="false"
      :showDownloadTbar="false"
      :showClearFiltersTbar="false"
      @query="handleQuery"
      @selection-change="handleSelectChange"
    >
      <template #column-version="scope">
        {{ `V${scope.data}` }}
      </template>
      <template #column-active="scope">
        {{ `${scope.data == 1 ? '是' : ''}` }}
      </template>
      <template #column-opera="scope">
        <el-popconfirm
          :title="`确定删除版本[ ${scope.row.version} ]吗?`"
          @confirm="handleDelete(scope.row.structureId, scope.row.version)"
        >
          <template #reference>
            <el-link plain type="danger" :underline="false" :icon="Remove">
              <span style="margin-left: 3px">删除</span>
            </el-link>
          </template>
        </el-popconfirm>
      </template>
    </x-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" :disabled="disabledOk" @click="handleOk">
          {{ okText }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import { ElDialog, ElLink, ElPopconfirm, ElMessage } from 'element-plus'
import { Remove } from '@element-plus/icons-vue'
import { util } from '@/utils'
import { formDefApi } from '@/api/modules/flow/formDef'
import { useFlowStore } from '@/stores/flow'
import type { VersionDialogType } from '@/typings'

const props = withDefaults(
  defineProps<{ visible: boolean; formId?: string; structureId?: string; mode?: VersionDialogType }>(),
  {
    visible: false
  }
)
const emits = defineEmits(['update:visible'])

const fs = useFlowStore()

const dialogVisible = computed(() => props.visible)

const refTable = ref()
const selectCount = computed(() => (refTable.value ? refTable.value.selection.length : 0))

const tableHeight = computed(() => util.getAppHeight() * 0.4)

const defaultColumns: any[] = [
  { prop: 'version', label: '版本', width: 100, search: false },
  { prop: 'updatedTime', label: '更新时间', search: false },
  { prop: 'active', label: '当前版本', width: 100, search: false, sortable: false }
]
const columns = computed(() => {
  if (props.mode == 'saveAs') {
    return defaultColumns
  } else if (props.mode == 'manage') {
    return defaultColumns.concat([
      { prop: 'structureId', scope: 'opera', label: '操作', width: 120, search: false, sortable: false }
    ])
  } else if (props.mode == 'clone') {
    return [{ prop: 'formName', label: '表单', width: 150 }].concat(defaultColumns)
  } else {
    return defaultColumns
  }
})
const title = computed(() => {
  if (props.mode == 'saveAs') {
    return '保存表单'
  } else if (props.mode == 'manage') {
    return '表单版本'
  } else if (props.mode == 'clone') {
    return '克隆表单'
  } else {
    return '表单'
  }
})
const okText = computed(() => {
  if (props.mode == 'saveAs') {
    if (selectCount.value > 0) {
      return `覆盖[ V${refTable.value.selection[0].version} ],并激活`
    } else {
      return '保存新版本,并激活'
    }
  } else if (props.mode == 'manage') {
    if (selectCount.value > 0) {
      return `激活[ V${refTable.value.selection[0].version} ]版本,并加载`
    } else {
      return '激活,并加载'
    }
  } else if (props.mode == 'clone') {
    if (selectCount.value > 0) {
      const selected = refTable.value.selection[0]
      return `克隆 ${selected.formName}[ V${selected.version} ]版本`
    } else {
      return '克 隆'
    }
  } else {
    return '确 定'
  }
})
const disabledOk = computed(() => {
  return selectCount.value == 0 && (props.mode == 'manage' || props.mode == 'clone')
})

const tableData = reactive({ resp: { list: [], total: 0 }, loading: false })
const handleQuery = (page: AxiosType.Pagination) => {
  tableData.loading = true
  let params = {}
  if (props.mode != 'clone') {
    params = { formId: props.formId }
  }
  formDefApi.findStructurePage(page, params).then(resp => {
    if (resp.success) {
      tableData.resp = resp.data
    }
    tableData.loading = false
  })
}

const handleSelectChange = (row: any) => {
  if (row.length > 1) {
    const del_row = row.shift()
    refTable.value.table.toggleRowSelection(del_row, false)
  }
}

const handleDelete = (structureId: string, name: string) => {
  formDefApi.deleteStructure(structureId).then(resp => {
    if (resp.success) {
      refTable.value.refresh()
      ElMessage.success(`版本[ ${name} ]已删除`)
    }
  })
}

watch(
  () => [props.formId, props.mode],
  () => {
    handleQuery({ pageNum: 1, pageSize: 30, sort: { formName: 'ascending', updatedTime: 'descending' }, filter: {} })
  }
)

const handleOk = () => {
  if (props.mode == 'saveAs') {
    if (fs.checkFormJson()) {
      if (selectCount.value > 0) {
        formDefApi.updateStructure(refTable.value.selection[0].structureId, fs.getFormJson()).then(callback)
      } else {
        formDefApi.createStructure(props.formId as string, fs.getFormJson()).then(callback)
      }
    }
  } else if (props.mode == 'manage') {
    if (selectCount.value > 0) {
      const selected = refTable.value.selection[0]
      if (selected.active == 0) {
        const structureId = selected.structureId
        formDefApi.activeStructure(props.formId as string, structureId).then(callback)
      }
    }
  } else if (props.mode == 'clone') {
    if (selectCount.value > 0) {
      const structureId = refTable.value.selection[0].structureId
      formDefApi.findStructureById(structureId).then(resp => {
        if (resp.success) {
          fs.comps = resp.data.formJson ? JSON.parse(resp.data.formJson).comps : []
          if (fs.comps && fs.comps.length > 0) {
            fs.activeComp(0)
          } else {
            fs.activeComp(-1)
          }
          ElMessage.success(`已克隆, 请及时保存`)
          emits('update:visible', false)
        }
      })
    }
  }
}

const callback = (resp: any) => {
  if (resp.success) {
    refTable.value.refresh()
    ElMessage.success(`${props.mode == 'saveAs' ? '表单已保存, ' : ''}V${resp.data.version} 版本已激活`)
    fs.updateActiveStructure(resp.data.structureId)
    fs.setData(resp.data)
    emits('update:visible', false)
  } else {
    ElMessage.error(resp.message)
  }
}

const handleCancel = () => {
  emits('update:visible', false)
}
</script>

<style lang="scss" scoped>
.tip {
  color: $--color-danger;
  font-size: $--size-font-small;
}
</style>
